﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace MSUS.Kinect.SkeletonTracker
{
	public static class Win32
	{
		[DllImport("user32.dll")]
		public static extern bool SetCursorPos(int X, int Y);

		[DllImport("user32.dll", SetLastError = true)]
		public static extern uint SendInput(UInt32 nInputs, INPUT[] pInputs, Int32 cbSize);

		[StructLayout(LayoutKind.Sequential)]
		public struct MOUSEINPUT
		{
			public int dx;
			public int dy;
			public uint mouseData;
			public uint dwFlags;
			public uint time;
			public IntPtr dwExtraInfo;
		}

		[StructLayout(LayoutKind.Sequential)]
		public struct KEYBDINPUT
		{
			public ushort wVk;
			public ushort wScan;
			public uint dwFlags;
			public uint time;
			public IntPtr dwExtraInfo;
		}

		[StructLayout(LayoutKind.Sequential)]
		public struct HARDWAREINPUT
		{
			public uint uMsg;
			public ushort wParamL;
			public ushort wParamH;
		}

		[StructLayout(LayoutKind.Explicit)]
		public struct INPUT
		{
			[FieldOffset(0)]
			public int type;
			[FieldOffset(4)] //[FieldOffset(8)] for x64
			public MOUSEINPUT mi;
			[FieldOffset(4)] //[FieldOffset(8)] for x64
			public KEYBDINPUT ki;
			[FieldOffset(4)] //[FieldOffset(8)] for x64
			public HARDWAREINPUT hi;
		}

		[DllImport("user32.dll")]
		static extern IntPtr GetMessageExtraInfo();

		const int INPUT_MOUSE = 0;
		const int INPUT_KEYBOARD = 1;
		const int INPUT_HARDWARE = 2;
		const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
		const uint KEYEVENTF_KEYUP = 0x0002;
		const uint KEYEVENTF_UNICODE = 0x0004;
		const uint KEYEVENTF_SCANCODE = 0x0008;
		const uint XBUTTON1 = 0x0001;
		const uint XBUTTON2 = 0x0002;
		const uint MOUSEEVENTF_MOVE = 0x0001;
		const uint MOUSEEVENTF_LEFTDOWN = 0x0002;
		const uint MOUSEEVENTF_LEFTUP = 0x0004;
		const uint MOUSEEVENTF_RIGHTDOWN = 0x0008;
		const uint MOUSEEVENTF_RIGHTUP = 0x0010;
		const uint MOUSEEVENTF_MIDDLEDOWN = 0x0020;
		const uint MOUSEEVENTF_MIDDLEUP = 0x0040;
		const uint MOUSEEVENTF_XDOWN = 0x0080;
		const uint MOUSEEVENTF_XUP = 0x0100;
		const uint MOUSEEVENTF_WHEEL = 0x0800;
		const uint MOUSEEVENTF_VIRTUALDESK = 0x4000;
		const uint MOUSEEVENTF_ABSOLUTE = 0x8000;


		public static void DoMouseClick(bool down)
		{
			INPUT[] inpArray = new INPUT[1];
			inpArray[0].type = Win32.INPUT_MOUSE;
			if (down)
				inpArray[0].mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
			else
				inpArray[0].mi.dwFlags = MOUSEEVENTF_LEFTUP;


			SendInput(1, inpArray, Marshal.SizeOf(typeof(INPUT)));
		}
	}
}
